package club.westudy.distributed.lock.internal.zookeeper;

import club.westudy.distributed.lock.DistributedLockService;
import club.westudy.distributed.lock.internal.InternalLockExecutorService;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class ZookeeperInternalLockExecutorService implements InternalLockExecutorService {
    CuratorFramework client;
    @Override
    public void initial(long guardScanTimeMs) {
        //创建zookeeper的客户端
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        client = CuratorFrameworkFactory.newClient("10.21.41.181:2181,10.21.42.47:2181,10.21.49.252:2181", retryPolicy);
        client.start();
    }

    @Override
    public void destroy() {
        client.close();
    }

    @Override
    public DistributedLockService.CriticalRegionContext acquire(String feature, long maxLeaseTimeMs, long tryLockWaitTimeMs) throws Exception {
        //创建分布式锁, 锁空间的根节点路径为/curator/lock
        InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock");
        mutex.acquire();
        return null;
    }

    @Override
    public void release(DistributedLockService.CriticalRegionContext criticalRegionContext) throws Exception {
        //创建分布式锁, 锁空间的根节点路径为/curator/lock
        InterProcessMutex mutex = new InterProcessMutex(client, "/curator/lock");
        mutex.release();
    }
}
